(function($) {
	var groupCode = '',groupDesc = '',locId = '',locDesc = '';
	var applyArr = null, receiveArr = null;
	var applyIndex = 1;
	var receiveIndex = 1;
	var oneNum = 20;
	var thisMonthStr = '';
	var applyLoading = false;
	var receiveLoading = false;
	var applyPullElement = null;	
	var receivePullElement = null;	
	var userpicker;
	$.init({
		swipeBack: true //启用右滑关闭功能
	});
	$.plusReady(function() {
		$('.mui-scroll-wrapper').scroll({
			indicators: false //是否显示滚动条
		});
		
		var currentLoc = getLocalData('currentLoc');
		if(currentLoc) {
			groupCode = currentLoc['GroupCode'];
			groupDesc = currentLoc['GroupDesc'];
			locId = currentLoc['LocId'];
			locDesc = currentLoc['LocDesc'];
		} else {
			mui.toast('用户未登录');
			mui.openWindow('logon-shell.html', 'logon-shell');
			return;
		}
		setupBtns();
		mui(".mui-progressbar").each(function() {
			mui(this).progressbar({
				progress: this.getAttribute("data-progress")
			}).show();
		});
		tabInitAndTapSetup(); //tabbar 切换方法
		var scrolls = document.querySelectorAll('.mui-slider-group .mui-scroll');
		mui.each(scrolls,function(index, pullRefreshEl){
			mui(pullRefreshEl).pullToRefresh({
				up: {
					callback: function() {
						if (index == 0) {
							applyPullElement = this;
							getApplyList();
						}else{
							receivePullElement = this;
							getReceiveList();
						}
					}
				}
			});
		});
		mui('#tab1Slider').slider().stopped = true;
		mui('#tab2Slider').slider().stopped = true;
		resetPullRefresh();
	});
	function getApplyList(){
		if (applyLoading) {
			return;
		}
		getApplyReceiveList('applyWrapper');
	}
	
	function getReceiveList(){
		if (receiveLoading) {
			return;
		}
		getApplyReceiveList('receiveWrapper');
	}
	function getApplyReceiveList(idStr) {
		var pageIndex = 1;
		var listType = '';
		if (idStr == 'applyWrapper') {
			listType = 'S1';
			applyLoading = true;
			pageIndex = applyIndex;
		}else{
			listType = 'S2';
			receiveLoading = true;
			pageIndex = receiveIndex;
		}
		
		plus.nativeUI.showWaiting("正在加载",{modal:false});
		var userID = getLocalData('pinfo').rw.toString();
		var startDate = document.getElementById('startDate');
		var currMonth = startDate.innerText
		var daysCount = getMonthMaxDay(currMonth);
		var stDateStr = currMonth + '-01';
		var endDateStr = currMonth + '-' + daysCount;
		var xmlStr = '<Request>' + locId + '^' + stDateStr + '^' + endDateStr + '^' +
			groupCode + '^' + userID + '^'+listType+'^^' + pageIndex + '^' + oneNum + '</Request>';
//		console.log('xmlStr:',xmlStr);
		postHttpRequest(xmlStr, 'nurse.stop.getnurleavelist', function(result) {
			plus.nativeUI.closeWaiting();
//			console.log('result',result);
			var dataArr = eval('(' + result + ')');
			if (idStr == 'applyWrapper' && applyArr == null) {
				applyArr = [];
			}else if (idStr == 'receiveWrapper' && receiveArr == null) {
				receiveArr = [];
			}
			for (var i = 0; i < dataArr.length;i++) {
				var oneDict = dataArr[i];
				if (idStr == 'applyWrapper') {
					applyArr.push(oneDict);
				}else{
					receiveArr.push(oneDict);
				}
			}
			updateTableView(dataArr,idStr);
			if (idStr == 'applyWrapper') {
				if (applyPullElement != null) {
					applyPullElement.endPullUpToRefresh(dataArr.length < oneNum);
				}
				applyLoading = false;
				applyIndex += 1;
			}else if (idStr == 'receiveWrapper') {
				if (receivePullElement != null) {
					receivePullElement.endPullUpToRefresh(dataArr.length < oneNum);
				}
				receiveLoading = false;
				receiveIndex += 1;
			}
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
			if (idStr == 'applyWrapper') {
				if (applyPullElement != null) {
					applyPullElement.endPullUpToRefresh(false);
				}
				applyLoading = false;
			}else if (idStr == 'receiveWrapper') {
				if (receivePullElement != null) {
					receivePullElement.endPullUpToRefresh(false);
				}
				receiveLoading = false;
			}
		});
	}
function updateTableView(dataArr,idStr) {
		var tableUlId = 'applyTableUl';
		var currSeg = 0;
		if (idStr == 'receiveWrapper') {
			tableUlId = 'receiveTableUl';
			currSeg = 1;
		}
		var tableUl = document.getElementById(tableUlId);
		var oldLength = tableUl.querySelectorAll('li').length;
		for(var i = 0; i < dataArr.length; i++) {
			var oneDict = dataArr[i];
			if (idStr == 'applyWrapper') {
				applyArr.push(oneDict);
			}else{
				receiveArr.push(oneDict);
			}
			var oneLi = document.createElement('li');
			oneLi.setAttribute('class', 'mui-table-view-cell');
			oneLi.id = currSeg +'-' + (oldLength + i);
			tableUl.appendChild(oneLi);
			var AddDate = oneDict['AddDate'].substr(5,5);
			var AddTime = oneDict['AddTime'].substr(0,5);
			var addDate = AddDate +'&nbsp;' + AddTime;
			var flag = oneDict['Flag'];
			var stateClass = '';
			if (flag == 'A') {
				stateClass = 'passed';
			}else if (flag == 'R') {
				stateClass = 'refused';
			}
			
			var applyer = oneDict['PerName']+'（' +oneDict['ApplicationPostDesc'] +'）'; 
			var shifter = oneDict['ShiftPerName']+'（' +oneDict['ShiftPostDesc'] +'）'; 
			oneLi.innerHTML = '<div class="applyTime">'+addDate+'</div>' +
				'<div class="label">申请人：</div>' +
				'<div class="labelKey amKey">' + applyer + '</div><div></div>' +
				'<div class="label">换班日期：</div>' +
				'<div class="labelKey">'+oneDict['ApplicationDate']+'</div><div></div>' +
				'<div class="label">换班对象：</div>' +
				'<div class="labelKey amKey">'+shifter+'</div><div></div>' +
				'<div class="label">换班日期：</div>' +
				'<div class="labelKey amKey">' + oneDict['ShiftDate'] + '</div><div></div>' +
				'<div class="statetip '+stateClass+'">' + oneDict['FlagDesc'] + '</div>';
			oneLi.addEventListener('tap', openApplyDetailPage, false);
		}
	}

	function openApplyDetailPage() {
		var idArr = this.id.split('-');
		var seg = parseInt(idArr[0]);
		var index = parseInt(idArr[1]);
		var oneDict;
		var typeStr = '';
		if (seg == 0) {
			typeStr = 'S1';
			oneDict = applyArr[index];
		}else{
			typeStr = 'S2';
			oneDict = receiveArr[index];
		}
		if (oneDict == null) {
			return;
		}
		plus.storage.removeItem('detail');
		mui.openWindow({
			url: "applyDetail.html",
			id: "applyDetail",
			extras: {
				type: typeStr,
				sourceData: oneDict
			}
		});
		var applyDetail = plus.webview.getWebviewById('applyDetail');
		if (applyDetail) {
			applyDetail.addEventListener('close',function(){
				var detail = plus.storage.getItem('detail');
				if (detail == '1') {
					resetPullRefresh();
				}
			});
		}
	}

	function setupBtns() {
		var today = getTodayStr();
		thisMonthStr = today.substring(0, today.length - 3);
		var startDate = document.getElementById('startDate');
		startDate.innerText = thisMonthStr;
		if (plus.os.name == 'iOS') {
			userpicker = new mui.xhPicker(2,'请选择月份','pickerId');
			var dateArr = []
			var monArr = []
			for (var i = 0; i < 12; i++) {
				var text = (i+1)
				if (text < 10) {
					text = '0'+text
				}
				monArr[i] = {'text':text}
			}
			var yearInt = new Date().getFullYear()-5;
			for (var i = 0; i < 10; i++) {
				dateArr[i] = {'text':yearInt+i,'children':monArr}
			}
			userpicker.setData(dateArr);
			startDate.addEventListener('tap', iOSSelectAbsentMonth, false);
		}else{
			startDate.addEventListener('tap', selectAbsentMonth, false);
		}
		var thisMonth = document.getElementById('thisMonth');
		thisMonth.addEventListener('tap', function() {
			var startDate = document.getElementById('startDate');
			startDate.innerText = thisMonthStr;
			resetPullRefresh();
		}, false);
		var lastMonth = document.getElementById('lastMonth');
		lastMonth.addEventListener('tap',function(){
			var startDate = document.getElementById('startDate');
			startDate.innerText = getFullLastMonth(startDate.innerText);
			resetPullRefresh();
		});
		var nextMonth = document.getElementById('nextMonth');
		nextMonth.addEventListener('tap',function(){
			var startDate = document.getElementById('startDate');
			startDate.innerText = getFullNextMonth(startDate.innerText);
			resetPullRefresh();
		});
		var applyBtn = document.getElementById('apply');
		applyBtn.addEventListener('tap', function(e) {
			plus.storage.removeItem('detail');
			mui.openWindow({
				url: "changeSchEdit.html",
				id: "changeSchEdit",
				extras: {}
			});
			var changeSchEdit = plus.webview.getWebviewById('changeSchEdit');
			if(changeSchEdit) {
				changeSchEdit.addEventListener('close', function() {
					var detail = plus.storage.getItem('detail');
					if (detail == '1') {
						resetPullRefresh();
					}
				});
			}
		});
	}

	function selectAbsentMonth() {
		var _self = this;
		if(_self.picker) {
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
				resetPullRefresh();
			});
		} else {
			var optionsJson = '{"type":"month"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
				resetPullRefresh();
			});
		}
	}
	function iOSSelectAbsentMonth(){
		var btnDom = this
		userpicker.show(function(items) {
			btnDom.innerText = items[0]['text']+'-'+items[1]['text'];
			resetPullRefresh();
		});
	}
	function resetPullRefresh(type) {
		var applyTableUl = document.getElementById('applyTableUl');
		applyTableUl.innerHTML = '';
		var receiveTableUl = document.getElementById('receiveTableUl');
		receiveTableUl.innerHTML = '';
		if (applyArr != null) {
			applyArr.splice(0,applyArr.length);
		}
		if (receiveArr != null) {
			receiveArr.splice(0,receiveArr.length);
		}
		applyIndex = 1;
		receiveIndex = 1;
		mui('#applyWrapper').scroll().scrollTo(0,0,100);
		mui('#receiveWrapper').scroll().scrollTo(0,0,100);
		if (applyPullElement) {
			applyPullElement.refresh(true);
		}
		getApplyList();
		if (receivePullElement) {
			receivePullElement.refresh(true);
		}
		getReceiveList();
	}

	function tabInitAndTapSetup() {
		var tab1 = document.getElementById('tab1');
		var tab2 = document.getElementById('tab2');
		var tab1Content = document.getElementById('tab1Content');
		var tab2Content = document.getElementById('tab2Content');

		tab1.addEventListener('tap', function() {
			if(!tab1.classList.contains('mui-active')) {
				tab2Content.classList.remove('mui-active');
				tab2Content.style.display = 'none';
				tab1Content.classList.add('mui-active');
				tab1Content.style.display = 'block';
			}
			if (applyArr == null) {
				if (applyPullElement) {
					applyPullElement.refresh(true);
				}
				getApplyList();
			}
		});
		tab2.addEventListener('tap', function() {
			if(!tab2Content.classList.contains('mui-active')) {
				tab1Content.classList.remove('mui-active');
				tab1Content.style.display = 'none';
				tab2Content.classList.add('mui-active');
				tab2Content.style.display = 'block';
			}
			if (receiveArr == null) {
				if (receivePullElement) {
					receivePullElement.refresh(true);
				}
				getReceiveList();
			}
		});
	}
	/*
	 * 列表接口
	 * DepId(病区)^StDate(开始日期)^EndDate(结束日期)^Group(安全组)^PerId(人员Id)^Type(类型)请假L换班S^页数:pnum^行数:limit
	 * {'rw':'17','DepId':'85','DepDesc':'QKYXKPTNKBF-全科医学科(普通内科)病房','PerId':'1020','PerName':'赵霞','ApplicationDate':'2020-01-20','ShiftPerId':'372','ShiftPerName':'范志宏','ShiftDate':'2020-01-21','LeaveExplain':'Tiao ban la','Flag':'V','FlagDesc':'待审批','AddDate':'2020-01-19','AddTime':'10:27:37','ApprovalPerName':'','ApprovalDate':'','ApprovalTime':'','ApprovalExplain':'','Type':'S','ApplicationPostDesc':'7′-12 2-5′','ShiftPostDesc':'6-8′A夜'}

	 * 
	 * 

	 * V:待审批;R:驳回;A:通过)

	 */

})(mui);